import { Button, Card, Descriptions, Form, Input, Space } from "antd";
import { useState } from "react";
import { getDnsApi, getToken } from "../utils/client";
import { DnsQueryPost200Response } from "@linksaas-minapp/netutil-api";

function DnsPanel() {
    const [hostName, setHostName] = useState("");
    const [result, setResult] = useState<DnsQueryPost200Response | null>(null);

    const queryDns = async () => {
        setResult(null);
        const api = getDnsApi();
        const res = await api.dnsQueryPost({
            dnsQueryPostRequest: {
                token: getToken(),
                addr: hostName,
            },
        });
        setResult(res);
    };

    return (
        <Card bordered={false} bodyStyle={{ height: "calc(100vh - 120px)", overflowY: "auto" }} extra={
            <Form layout="inline">
                <Form.Item label="网络地址">
                    <Input value={hostName} onChange={e => {
                        e.stopPropagation();
                        e.preventDefault();
                        setHostName(e.target.value.trim());
                    }} />
                </Form.Item>
                <Form.Item>
                    <Button type="primary" disabled={hostName == ""} onClick={e => {
                        e.stopPropagation();
                        e.preventDefault();
                        queryDns();
                    }}>查询</Button>
                </Form.Item>
            </Form>
        }>
            {result != null && (
                <Descriptions column={1} labelStyle={{width:"60px"}}>
                    <Descriptions.Item label="A">{(result.a ?? []).join(",")}</Descriptions.Item>
                    {(result.cname ?? "") !== "" && (
                        <Descriptions.Item label="CNAME">{result.cname ?? ""}</Descriptions.Item>
                    )}
                    {(result.mx ?? []).length > 0 && (
                        <Descriptions.Item label="MX">
                            <Space direction="vertical">
                                {(result.mx ?? []).map(item => (
                                    <div key={item.host}>{item.host}({item.pref})</div>
                                ))}
                            </Space>
                        </Descriptions.Item>
                    )}
                    {(result.txt ??[]).length > 0 && (
                        <Descriptions.Item label="TXT">
                            <Space direction="vertical">
                                {(result.txt ?? []).map(item => (
                                    <div key={item}>{item}</div>
                                ))}
                            </Space>
                        </Descriptions.Item>
                    )}
                </Descriptions>
            )}
        </Card>
    );
}

export default DnsPanel;